package Viewer;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTree;
import javax.swing.JSlider;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import Controller.AbstractController;
import Controller.XMLController;
import Viewer.noteType;
import Viewer.Notes;
import Model.Chord;
import Model.PDFmanager;
import Model.Setting;
import Model.Song;
import Model.XMLManager;

import javax.swing.border.LineBorder;

import java.awt.Color;

import javax.swing.JRadioButton;

import java.awt.Checkbox;
import java.awt.Font;
import java.awt.Component;

import javax.swing.Box;
import javax.swing.JCheckBox;

@SuppressWarnings("serial")
public class MainWindow extends AbstractView {

	private JFrame frame;
	JTextField titleBox;
	JTextField ArtistBox;
	JTextArea TextArea;
	private JTextField FindBox;
	String pathSeparator;
	JTabbedPane tabbedPane;
	JPanel CanzonierePanel;
	JLabel lblCerca;
	JComboBox searchComboBox;
	JComboBox SOcomboBox;
	DefaultTreeModel dm;
	DefaultMutableTreeNode rootNode;

	JTree SongTree;
	JTree chordsTree;

	JSlider slider;
	JLabel minSlider;
	JLabel maxSlider;
	JLabel lblPdfFolder;
	JScrollPane scrollPane_1;
	public JTextArea VisualizzazioneArea;
	JPanel NewSongPanel;
	JLabel lblTitle;
	JLabel lblArtist;
	JLabel picLabel;

	NotificationToController btnGeneraPdf;
	NotificationToController AddSongbutton;
	NotificationToController btnDefinePath;
	NotificationToController btnSaveSONGS;
	NotificationToController ResetButton;
	NotificationToController btnCerca;
	NotificationToController btnModifica;
	NotificationToController Cancel;
	NotificationToController Modify;
	NotificationToController btnDelete;
	NotificationToController btnGenerateFullPDF;
	NotificationToController btnChooseChordPath;
	NotificationToController btnSelectImage;
	NotificationToController btnSalvaImpostazioni;

	JPanel GuitarPanel;
	JPanel SettingsPanel;
	JPanel ChordPanel;
	JPanel panel_1;
	JScrollPane scrollPane;
	JScrollPane scrollPane_2;
	JScrollPane scrollPane_3;

	PDFmanager manager = new PDFmanager();
	XMLManager xmlManager = new XMLManager();
	JTextField PathTextField;
	private JTextField ImagePathField;

	// gestione aggiunta accordi
	JLabel lblImagePath;
	JComboBox AddChordcomboBox;
	ButtonGroup chordRadioGroup;
	JRadioButton rdbtnStd;
	JRadioButton rdbtnDiesis;
	JRadioButton rdbtnB;
	JPanel newChordPanel;
	NotificationToController btnAddChord;
	NotificationToController btnDeleteChord;
	NotificationToController MIbasso;
	NotificationToController LA;
	NotificationToController RE;
	NotificationToController SOL;
	NotificationToController SI;
	NotificationToController MI;
	private JLabel lblNomeAccordo;
	private JTextField ChordName;
	private JLabel lblMi;
	private JLabel lblLa;
	private JLabel lblRe;
	private JLabel lblSol;
	private JLabel lblSi;
	private JLabel label_4;
	private JTextField chordsPathField;
	JCheckBox checkBoxAutomatico;

	/**
	 * Create the application.
	 */
	public MainWindow(AbstractController controller) {
		super(controller);
		// initialize();
		controller.setRegisteredView(this);

	}

	/**
	 * Initialize the contents of the frame.
	 */
	protected void initializeGUI() {
		frame = new JFrame();
		frame.setBounds(100, 100, 795, 675);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(6, 6, 783, 641);

		/**
		 * commentare la prima per avviarlo e la seconda per editare
		 * 
		 * TODO: segnalibro
		 */

		 frame.getContentPane().add(tabbedPane);
//		getContentPane().add(tabbedPane);

		CanzonierePanel = new JPanel();
		tabbedPane.addTab("Canzoniere", null, CanzonierePanel, null);
		CanzonierePanel.setLayout(null);

		FindBox = new JTextField();
		FindBox.setBounds(67, 6, 193, 28);
		FindBox.setColumns(10);
		CanzonierePanel.add(FindBox);

		lblCerca = new JLabel("Cerca");
		lblCerca.setBounds(18, 12, 61, 16);
		CanzonierePanel.add(lblCerca);

		searchComboBox = new JComboBox();
		searchComboBox.setModel(new DefaultComboBoxModel(new String[] {
				"Artista", "Titolo" }));
		searchComboBox.setBounds(18, 47, 113, 27);
		CanzonierePanel.add(searchComboBox);

		btnCerca = new NotificationToController();
		btnCerca.setText("Cerca");
		btnCerca.setTypeButton(TypeButton.SEARCH);
		btnCerca.setBounds(143, 46, 117, 29);
		CanzonierePanel.add(btnCerca);

		rootNode = new DefaultMutableTreeNode("Root Node");
		dm = new DefaultTreeModel(rootNode);

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(272, 47, 620, 667);
		CanzonierePanel.add(scrollPane_1);

		VisualizzazioneArea = new JTextArea();
		VisualizzazioneArea.setEditable(false);
		scrollPane_1.setViewportView(VisualizzazioneArea);

		scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(18, 178, 242, 370);
		CanzonierePanel.add(scrollPane_2);

		SongTree = new JTree(dm);
		scrollPane_2.setViewportView(SongTree);

		ResetButton = new NotificationToController();
		ResetButton.setText("Reset");
		ResetButton.setTypeButton(TypeButton.RESET);
		ResetButton.setBounds(143, 72, 117, 29);
		CanzonierePanel.add(ResetButton);

		btnDelete = new NotificationToController();
		btnDelete.setText("Cancella");
		btnDelete.setTypeButton(TypeButton.DELETESONG);
		btnDelete.setBounds(143, 137, 117, 29);
		btnDelete.setEnabled(false);
		CanzonierePanel.add(btnDelete);

		btnModifica = new NotificationToController();
		btnModifica.setTypeButton(TypeButton.MODIFY);
		btnModifica.setText("Modifica");
		btnModifica.setBounds(18, 137, 117, 29);
		btnModifica.setEnabled(false);
		CanzonierePanel.add(btnModifica);

		btnGenerateFullPDF = new NotificationToController();
		btnGenerateFullPDF.setTypeButton(TypeButton.GENERATEFULLPDF);
		btnGenerateFullPDF.setText("Genera PDF completo");
		btnGenerateFullPDF.setBounds(18, 560, 242, 29);
		CanzonierePanel.add(btnGenerateFullPDF);

		NewSongPanel = new JPanel();
		tabbedPane.addTab("Nuovo Brano", null, NewSongPanel, null);
		NewSongPanel.setLayout(null);

		titleBox = new JTextField();
		titleBox.setBounds(6, 100, 220, 28);
		titleBox.setColumns(10);
		NewSongPanel.add(titleBox);

		lblTitle = new JLabel("Titolo");
		lblTitle.setBounds(16, 72, 61, 16);
		NewSongPanel.add(lblTitle);

		lblArtist = new JLabel("Artista");
		lblArtist.setBounds(16, 8, 61, 16);
		NewSongPanel.add(lblArtist);

		ArtistBox = new JTextField();
		ArtistBox.setBounds(6, 32, 220, 28);
		ArtistBox.setColumns(10);
		NewSongPanel.add(ArtistBox);

		btnGeneraPdf = new NotificationToController();
		btnGeneraPdf.setText("Genera PDF");
		btnGeneraPdf.setTypeButton(TypeButton.SONGPDFGENERATION);
		btnGeneraPdf.setBounds(29, 177, 173, 29);
		NewSongPanel.add(btnGeneraPdf);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(238, 6, 518, 583);
		NewSongPanel.add(scrollPane);

		TextArea = new JTextArea();
		scrollPane.setViewportView(TextArea);

		AddSongbutton = new NotificationToController();
		AddSongbutton.setText("Aggiungi al canzoniere");
		AddSongbutton.setTypeButton(TypeButton.ADDSONG);
		AddSongbutton.setBounds(29, 140, 173, 29);
		NewSongPanel.add(AddSongbutton);

		Modify = new NotificationToController();
		Modify.setTypeButton(TypeButton.YESBUTTON);
		Modify.setText("Modifica");
		Modify.setBounds(6, 519, 173, 29);
		Modify.setVisible(false);
		NewSongPanel.add(Modify);

		Cancel = new NotificationToController();
		Cancel.setTypeButton(TypeButton.NOBUTTON);
		Cancel.setText("Chiudi");
		Cancel.setBounds(6, 560, 173, 29);
		Cancel.setVisible(false);
		NewSongPanel.add(Cancel);

		chordRadioGroup = new ButtonGroup();

		GuitarPanel = new JPanel();
		tabbedPane.addTab("Guitar Tools", null, GuitarPanel, null);
		GuitarPanel.setLayout(null);

		scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(19, 21, 180, 534);
		GuitarPanel.add(scrollPane_3);

		chordsTree = new JTree();
		scrollPane_3.setViewportView(chordsTree);

		ChordPanel = new JPanel();
		ChordPanel.setBounds(211, 21, 191, 206);
		GuitarPanel.add(ChordPanel);
		ChordPanel.setLayout(null);

		newChordPanel = new JPanel();
		newChordPanel.setBorder(new LineBorder(Color.GRAY));
		newChordPanel.setBounds(414, 21, 346, 217);
		GuitarPanel.add(newChordPanel);
		newChordPanel.setLayout(null);

		rdbtnStd = new JRadioButton("STD");
		rdbtnStd.setSelected(true);
		rdbtnStd.setBounds(165, 6, 64, 23);
		newChordPanel.add(rdbtnStd);

		rdbtnDiesis = new JRadioButton("#");
		rdbtnDiesis.setBounds(165, 30, 64, 23);
		newChordPanel.add(rdbtnDiesis);

		rdbtnB = new JRadioButton("b");
		rdbtnB.setBounds(165, 56, 64, 23);
		newChordPanel.add(rdbtnB);
		chordRadioGroup.add(rdbtnB);
		chordRadioGroup.add(rdbtnDiesis);
		chordRadioGroup.add(rdbtnStd);

		AddChordcomboBox = new JComboBox();
		AddChordcomboBox.setModel(new DefaultComboBoxModel(new String[] { "DO",
				"RE", "MI", "FA", "SOL", "LA", "SI" }));
		AddChordcomboBox.setBounds(16, 6, 97, 27);
		newChordPanel.add(AddChordcomboBox);

		lblImagePath = new JLabel("Immagine");
		lblImagePath.setBounds(16, 126, 97, 16);
		newChordPanel.add(lblImagePath);

		ImagePathField = new JTextField();
		ImagePathField.setBounds(16, 144, 189, 28);
		newChordPanel.add(ImagePathField);
		ImagePathField.setColumns(10);

		btnAddChord = new NotificationToController();
		btnAddChord.setTypeButton(TypeButton.ADDCHORD);
		btnAddChord.setBounds(16, 182, 117, 29);
		btnAddChord.setText("ADD Chord");
		newChordPanel.add(btnAddChord);

		lblNomeAccordo = new JLabel("Dettagli Accordo");
		lblNomeAccordo.setBounds(16, 88, 137, 16);
		newChordPanel.add(lblNomeAccordo);

		ChordName = new JTextField();
		ChordName.setColumns(10);
		ChordName.setBounds(140, 82, 80, 28);
		newChordPanel.add(ChordName);

		btnDeleteChord = new NotificationToController();
		btnDeleteChord.setTypeButton(TypeButton.DELETECHORD);
		btnDeleteChord.setText("DELETE Chord");
		btnDeleteChord.setBounds(223, 182, 117, 29);
		btnDeleteChord.setEnabled(false);
		newChordPanel.add(btnDeleteChord);

		btnSelectImage = new NotificationToController();
		btnSelectImage.setTypeButton(TypeButton.SELECTIMAGE);
		btnSelectImage.setText("Scegli...");
		btnSelectImage.setBounds(223, 145, 117, 29);
		newChordPanel.add(btnSelectImage);

		panel_1 = new JPanel();
		panel_1.setBounds(211, 239, 549, 316);
		GuitarPanel.add(panel_1);
		panel_1.setLayout(null);

		pathSeparator="/";
		String localPath =pathSeparator + "Resources"+ pathSeparator + "manico.png";
		ImageIcon icon = new ImageIcon(
				MainWindow.class.getResource(localPath));
		JLabel picLabel = new JLabel(icon);
		picLabel.setBounds(71, 0, 437, 310);
		picLabel.setIcon(icon);
		panel_1.add(picLabel);

		MIbasso = new NotificationToController();
		MIbasso.setTypeButton(TypeButton.MIBASSO);
		MIbasso.setBounds(77, 19, 431, 43);
		panel_1.add(MIbasso);

		LA = new NotificationToController();
		LA.setTypeButton(TypeButton.LA);
		LA.setBounds(77, 60, 431, 49);
		panel_1.add(LA);

		RE = new NotificationToController();
		RE.setTypeButton(TypeButton.RE);
		RE.setBounds(77, 111, 431, 43);
		panel_1.add(RE);

		SOL = new NotificationToController();
		SOL.setTypeButton(TypeButton.SOL);
		SOL.setBounds(77, 156, 431, 43);
		panel_1.add(SOL);

		SI = new NotificationToController();
		SI.setTypeButton(TypeButton.SI);
		SI.setBounds(77, 200, 431, 49);
		panel_1.add(SI);

		MI = new NotificationToController();
		MI.setTypeButton(TypeButton.MICANTINO);
		MI.setBounds(77, 248, 431, 43);
		panel_1.add(MI);

		lblMi = new JLabel("MI");
		lblMi.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblMi.setBounds(21, 27, 28, 16);
		panel_1.add(lblMi);

		lblLa = new JLabel("LA");
		lblLa.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblLa.setBounds(21, 75, 28, 16);
		panel_1.add(lblLa);

		lblRe = new JLabel("RE");
		lblRe.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblRe.setBounds(21, 124, 28, 16);
		panel_1.add(lblRe);

		lblSol = new JLabel("SOL");
		lblSol.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblSol.setBounds(21, 171, 28, 16);
		panel_1.add(lblSol);

		lblSi = new JLabel("SI");
		lblSi.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblSi.setBounds(21, 221, 28, 16);
		panel_1.add(lblSi);

		label_4 = new JLabel("MI");
		label_4.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		label_4.setBounds(21, 267, 28, 16);
		panel_1.add(label_4);

		picLabel = new JLabel("");
		picLabel.setBounds(0, 0, 191, 206);
		ChordPanel.add(picLabel);

		SettingsPanel = new JPanel();
		tabbedPane.addTab("Save & Settings", null, SettingsPanel, null);
		SettingsPanel.setLayout(null);

		lblPdfFolder = new JLabel("Cartella PDF");
		lblPdfFolder.setBounds(23, 27, 116, 16);
		SettingsPanel.add(lblPdfFolder);

		PathTextField = new JTextField();
		// PathTextField.setText("PDF_Songs/");
		PathTextField.setBounds(131, 21, 454, 28);
		PathTextField.setEditable(false);
		SettingsPanel.add(PathTextField);
		PathTextField.setColumns(10);

		btnDefinePath = new NotificationToController();
		btnDefinePath.setTypeButton(TypeButton.SELECTPATH);
		btnDefinePath.setText("Scegli..");
		btnDefinePath.setBounds(597, 22, 116, 29);
		SettingsPanel.add(btnDefinePath);

		

		JLabel lblAccordiPath = new JLabel("Cartella Accordi");
		lblAccordiPath.setBounds(23, 82, 116, 16);
		SettingsPanel.add(lblAccordiPath);

		btnChooseChordPath = new NotificationToController();
		btnChooseChordPath.setTypeButton(TypeButton.SELECTPATHCHORD);
		btnChooseChordPath.setText("Scegli..");
		btnChooseChordPath.setBounds(597, 77, 116, 29);
		SettingsPanel.add(btnChooseChordPath);

		chordsPathField = new JTextField();
		chordsPathField.setEditable(false);
		chordsPathField.setColumns(10);
		chordsPathField.setBounds(131, 76, 454, 28);
		SettingsPanel.add(chordsPathField);

		btnSaveSONGS = new NotificationToController();
		btnSaveSONGS.setTypeButton(TypeButton.SAVEBUTTON);
		btnSaveSONGS.setText("Salva");
		btnSaveSONGS.setBounds(197, 129, 117, 29);
		SettingsPanel.add(btnSaveSONGS);

		JLabel lblSalvaCanzoniere = new JLabel("Salva il Canzoniere");
		lblSalvaCanzoniere.setBounds(23, 134, 188, 16);
		SettingsPanel.add(lblSalvaCanzoniere);

		JLabel lblSistemaOperativo = new JLabel("Sistema Operativo");
		lblSistemaOperativo.setBounds(23, 220, 188, 16);
		SettingsPanel.add(lblSistemaOperativo);

		SOcomboBox = new JComboBox();
		SOcomboBox.setModel(new DefaultComboBoxModel(new String[] {"Mac OS" , "Windows"
				}));
		SOcomboBox.setBounds(197, 216, 142, 27);
		SettingsPanel.add(SOcomboBox);
		
		btnSalvaImpostazioni= new NotificationToController();
		btnSalvaImpostazioni.setTypeButton(TypeButton.SAVESETTINGS);
		btnSalvaImpostazioni.setText("Salva Impostazioni");
		btnSalvaImpostazioni.setBounds(213, 516, 188, 29);
		SettingsPanel.add(btnSalvaImpostazioni);
		
		JLabel lblSalvataggioAutomatico = new JLabel("Salvataggio automatico");
		lblSalvataggioAutomatico.setBounds(23, 170, 162, 23);
		SettingsPanel.add(lblSalvataggioAutomatico);
		
		checkBoxAutomatico = new JCheckBox("");
		checkBoxAutomatico.setBounds(197, 170, 35, 23);
		SettingsPanel.add(checkBoxAutomatico);

		this.frame.setVisible(true);
		this.setResizable(false);

	}

	public void cleanBoxes() {
		TextArea.setText("");
		ArtistBox.setText("");
		titleBox.setText("");
	}
	
	public boolean getSalvataggioAutomatico()
	{
		return checkBoxAutomatico.isSelected();
	}
	
	
	/**
	 * Metodo che restituisce la stringa dell'artista inserita dall'utente
	 * 
	 * @return la stringa contenente l'artista
	 */

	public String getArtist() {
		return ArtistBox.getText();
	}

	/**
	 * Metodo che restituisce la stringa del titolo inserita dall'utente
	 * 
	 * @return la stringa contenente il titolo
	 */

	public String getTitle() {
		return titleBox.getText();
	}

	/**
	 * Metodo che restituisce la stringa del titolo inserita dall'utente
	 * 
	 * @return l'array di stringhe contenente le righe
	 */
	public String[] getTesto() {
		// metto in un array ogni riga
		String[] lines = TextArea.getText().split("\\n");
		return lines;

	}

	public String getFullText() {
		// metto in un array ogni riga
		String fullText = TextArea.getText();
		return fullText;

	}

	/**
	 * metodo che restituisce il tipo di nota da inserire
	 * 
	 * @return
	 */
	public noteType getNoteType() {

		if (rdbtnStd.isSelected())
			return noteType.STD;
		else if (rdbtnDiesis.isSelected())
			return noteType.DIESIS;
		else
			return noteType.BEMOLLE;
	}

	/**
	 * metodo che restituisce la nota da inserire
	 * 
	 * @return
	 */
	public Notes getNote() {

		if (AddChordcomboBox.getSelectedItem().equals("DO"))
			return Notes.DO;
		else if (AddChordcomboBox.getSelectedItem().equals("RE"))
			return Notes.RE;
		else if (AddChordcomboBox.getSelectedItem().equals("MI"))
			return Notes.MI;
		else if (AddChordcomboBox.getSelectedItem().equals("FA"))
			return Notes.FA;
		else if (AddChordcomboBox.getSelectedItem().equals("SOL"))
			return Notes.SOL;
		else if (AddChordcomboBox.getSelectedItem().equals("LA"))
			return Notes.LA;
		else
			return Notes.SI;
	}

	/**
	 * metodo che restituisce il nome della nota da inserire
	 * 
	 * @return
	 */
	public String getChordName() {

		String name = AddChordcomboBox.getSelectedItem().toString();

		if (rdbtnDiesis.isSelected())
			name = name + "#";
		else if (rdbtnB.isSelected())
			name = name + "b";
		name = name + ChordName.getText();
		return name;
	}

	public void generatePDF(Song s, String pDFSavepath) {

		manager.createPDFSong(s, pDFSavepath);
	}
	/**
	 * TODO: listener
	 */
	@Override
	protected void addListeners() {

		btnGeneraPdf.addActionListener(this.getController());
		AddSongbutton.addActionListener(this.getController());
		btnDefinePath.addActionListener(this.getController());
		btnSaveSONGS.addActionListener(this.getController());
		btnAddChord.addActionListener(this.getController());
		ResetButton.addActionListener(this.getController());
		btnCerca.addActionListener(this.getController());
		btnModifica.addActionListener(this.getController());
		Cancel.addActionListener(this.getController());
		Modify.addActionListener(this.getController());
		btnDelete.addActionListener(this.getController());
		MIbasso.addActionListener(this.getController());
		LA.addActionListener(this.getController());
		RE.addActionListener(this.getController());
		SOL.addActionListener(this.getController());
		SI.addActionListener(this.getController());
		MI.addActionListener(this.getController());
		btnDeleteChord.addActionListener(this.getController());
		btnGenerateFullPDF.addActionListener(this.getController());
		btnChooseChordPath.addActionListener(this.getController());
		btnSelectImage.addActionListener(this.getController());
		btnSalvaImpostazioni.addActionListener(this.getController());

		// listener del cambio selezione nodo

		addJtreeSongListener();
		addJtreeChordsListener();

		// listener di chiusura finestra

		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				// ExitController ExitController = new ExitController();
				// ExitView Exitwindow = new ExitView(ExitController);
			}
		});

	}

	private void addJtreeSongListener() {
		SongTree.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				String[] array = { "" };
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) SongTree
						.getLastSelectedPathComponent();
				if (selectedNode != null && selectedNode.isLeaf()
						&& !isRoot(selectedNode))
					// &&!selectedNode.toString().equalsIgnoreCase("Root Node"))
					array = getsongfromNode(selectedNode);

				String testo = "";
				for (String string : array) {
					testo = testo + string + "\n";
				}
				if (selectedNode != null)
					checkIsLeaf(selectedNode);
				VisualizzazioneArea.setText(testo);
			}

		});
		// fine

	}

	

	private void addJtreeChordsListener() {
		chordsTree.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) chordsTree
						.getLastSelectedPathComponent();
				if (selectedNode != null
						&& selectedNode.isLeaf()
						&& !isRoot(selectedNode)
						&& (!selectedNode.toString().equalsIgnoreCase("b")
								&& !selectedNode.toString().equalsIgnoreCase(
										"#") && !selectedNode.toString()
								.equalsIgnoreCase("STD"))) {
					btnDeleteChord.setEnabled(true);
					// test
					if (picLabel != null)
						ChordPanel.remove(picLabel);

					String fullPath = getChordspath() + pathSeparator
							+ selectedNode.toString() + ".png";
					File image = new File(fullPath);

					if (!image.exists()) {
						ImageIcon icon = new ImageIcon(MainWindow.class
								.getResource(pathSeparator+"Resources"+pathSeparator+"noimage.png"));
						picLabel = new JLabel(icon);
						picLabel.setBounds(0, 0, 191, 206);
						picLabel.setIcon(icon);
						ChordPanel.add(picLabel);
						ChordPanel.repaint();

					} else {
						ImageIcon icon = new ImageIcon(fullPath);
						picLabel = new JLabel(icon);
						picLabel.setBounds(0, 0, 191, 206);
						picLabel.setIcon(icon);
						ChordPanel.add(picLabel);
						ChordPanel.repaint();
					}

				} else
					btnDeleteChord.setEnabled(false);
			}

		});
		// fine

	}

	private String[] getsongfromNode(DefaultMutableTreeNode selectedNode) {

		// System.out.println(selectedNode);
		String title = selectedNode.toString();
		String Singer = selectedNode.getParent().toString();
		List<Song> lista = null;
		String[] array = { "" };

		// chiedo la lista al controller
		if (this.getController() instanceof XMLController) {
			XMLController contr = (XMLController) this.getController();
			lista = contr.getSongsList();
		}

		// cerco la canzone nella lista
		if (lista != null) {
			for (Song song : lista) {
				if (song.getSinger().equalsIgnoreCase(Singer)
						&& song.getTitle().equalsIgnoreCase(title)) {
					array = song.getText();
					return array;
				}
			}
		}
		return array;
	}

	public void generatePDFSongBook(List<Song> songBook, String path) {
		for (Song song : songBook) {
			manager.createPDFSong(song, path);
		}

	}

	public void generatePDFindex(List<Song> songBook, String pDFSavepath) {

		manager.createPDFIndex(songBook, pDFSavepath, "Indice");

	}

	protected DefaultMutableTreeNode findSinger(TreeModel model,
			Object rootNode, String singer) {
		int cc;
		cc = model.getChildCount(rootNode);
		for (int i = 0; i < cc; i++) {
			Object child = model.getChild(rootNode, i);
			if (child.toString().equalsIgnoreCase(singer))
				return (DefaultMutableTreeNode) child;
			else {
				// non fare niente
			}

		}
		return null;
	}

	public void cleanChordsBoxes() {
		rdbtnStd.setSelected(true);
		AddChordcomboBox.setSelectedItem("DO");
		ChordName.setText("");
		ImagePathField.setText("");

	}

	public void LoadJtreeNEW(List<Song> canzoniere) {

		SongTree.clearSelection();

		DefaultMutableTreeNode root = new DefaultMutableTreeNode(
				"Il mio canzoniere");
		DefaultTreeModel model = new DefaultTreeModel(root);
		DefaultMutableTreeNode SingerNodeParent = null;

		for (Song song : canzoniere) {
			DefaultMutableTreeNode SingerNode = new DefaultMutableTreeNode(
					song.getSinger());
			DefaultMutableTreeNode SongNode = new DefaultMutableTreeNode(
					song.getTitle());
			SingerNodeParent = findSinger(model, root, song.getSinger());
			if (SingerNodeParent != null)
				SingerNodeParent.add(SongNode);

			// se non trovo l'artista
			else {
				SingerNode.add(SongNode);
				root.add(SingerNode);
				SingerNodeParent = SingerNode;
				// fine
			}
			SingerNodeParent = null;
		}
		this.cleanParents(model, root);
		model.reload(root);

		SongTree.setModel(model);

	}

	public void LoadChordsJtree(List<Chord> accordi) {

		SongTree.clearSelection();

		DefaultMutableTreeNode root = new DefaultMutableTreeNode(
				"I miei accordi");
		DefaultTreeModel model = new DefaultTreeModel(root);
		DefaultMutableTreeNode STD = new DefaultMutableTreeNode("STD");
		DefaultMutableTreeNode DIESIS = new DefaultMutableTreeNode("#");
		DefaultMutableTreeNode BEMOLLE = new DefaultMutableTreeNode("b");

		if (accordi.size() == 0) {
			root.add(BEMOLLE);
			root.add(DIESIS);
			root.add(STD);
			DefaultTreeModel model_empty = new DefaultTreeModel(root);
			model_empty.reload(root);
			chordsTree.setModel(model_empty);
		}

		else {

			
			DefaultMutableTreeNode NotaNodeOLD = new DefaultMutableTreeNode();
			boolean diesis = true;
			boolean bemolle = true;
			
			for (Chord chord : accordi) {
				
				
				
				if (chord.getType() == noteType.STD) {

					DefaultMutableTreeNode NotaNode = new DefaultMutableTreeNode(
							chord.getNote());
					DefaultMutableTreeNode NomeNode = new DefaultMutableTreeNode(
							chord.getNoteName());
					// Se trovo la nota
					if (NotaNode.toString().equals(NotaNodeOLD.toString()))
						NotaNodeOLD.add(NomeNode);
					// se non trovo la nota
					else {
						NotaNode.add(NomeNode);
						STD.add(NotaNode);
						root.add(STD);
						NotaNodeOLD = NotaNode;
						// fine
					}
				}

				else if (chord.getType() == noteType.DIESIS) {
					if(diesis){
						NotaNodeOLD = new DefaultMutableTreeNode();
					diesis=false;
					}
					DefaultMutableTreeNode NotaNode = new DefaultMutableTreeNode(
							chord.getNote());
					DefaultMutableTreeNode NomeNode = new DefaultMutableTreeNode(
							chord.getNoteName());
					// Se trovo la nota
					if (NotaNode.toString().equals(NotaNodeOLD.toString()))
						NotaNodeOLD.add(NomeNode);

					// se non trovo la nota
					else {
						NotaNode.add(NomeNode);
						DIESIS.add(NotaNode);
						root.add(DIESIS);
						NotaNodeOLD = NotaNode;
						// fine
					}
				}

				else {
					
					if(bemolle){
						NotaNodeOLD = new DefaultMutableTreeNode();
						bemolle=false;
					}
					DefaultMutableTreeNode NotaNode = new DefaultMutableTreeNode(
							chord.getNote());
					DefaultMutableTreeNode NomeNode = new DefaultMutableTreeNode(
							chord.getNoteName());
					// Se trovo la nota
					if (NotaNode.toString().equals(NotaNodeOLD.toString()))
						NotaNodeOLD.add(NomeNode);

					// se non trovo la nota
					else {
						NotaNode.add(NomeNode);
						BEMOLLE.add(NotaNode);
						root.add(BEMOLLE);
						NotaNodeOLD = NotaNode;
						// fine
					}
				}
				
			}
			cleanChordsParent(model, root);

			model.reload(root);

			chordsTree.setModel(model);
		}
	}

	// scan a partire da un nodo
	protected void walk4Artist(DefaultTreeModel model, Object root, String str) {
		int cc;
		cc = model.getChildCount(root);

		String childName;

		for (int i = 0; i < cc; i++) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) model
					.getChild(root, i);
			childName = child.toString().toLowerCase();

			// System.out.println("Confronto: " + childName + " " +
			// childName.length());
			// System.out.println("Con: " + str + " " + str.length());

			if (!childName.contains(str.toLowerCase())) {
				// System.out.println("rimuovo: " + child.toString());

				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) child
						.getParent();
				// System.out.println("Numero figli: " +
				// parent.getChildCount());
				// System.out.println("Figlio numero: " +
				// parent.getIndex(child));

				parent.remove(child);
				cc = model.getChildCount(root);
				i--;

			}

		}
		model.reload();
	}

	protected void walk4Title(DefaultTreeModel model, Object root, String str) {
		int cc;
		cc = model.getChildCount(root);

		for (int i = 0; i < cc; i++) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) model
					.getChild(root, i);

			if (model.isLeaf(child)) {
				String title = child.toString().toLowerCase();
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) child
						.getParent();
				if (!title.contains(str.toLowerCase())) {
					parent.remove(child);
					cc = model.getChildCount(parent);
					i--;
				}
			}

			else {
				walk4Title(model, child, str);
			}

		}
		model.reload();
	}

	
	public void Search(String str) {

		// reset dell'albero
		List<Song> canzoniere = null;

		if (this.getController() instanceof XMLController) {
			XMLController contr = (XMLController) this.getController();
			canzoniere = contr.getSongsList();
			LoadJtreeNEW(canzoniere);
		}

		if (searchComboBox.getSelectedItem().toString()
				.equalsIgnoreCase("Artista")) {

			Search4Artist(str);

		}

		else {
			if (canzoniere != null)
				// Search4Title(canzoniere, str);
				Search4Title(str);

		}

	}

	private void Search4Title(String str) {
		DefaultTreeModel model = (DefaultTreeModel) SongTree.getModel();
		if (model != null) {
			Object root = model.getRoot();
			walk4Title(model, root, str);
			cleanParents(model, root);

			SongTree.setModel(model);
		} else
			System.out.println("Tree is empty.");

	}

	private void cleanParents(DefaultTreeModel model, Object root) {
		int cc;
		cc = model.getChildCount(root);

		for (int i = 0; i < cc; i++) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) model
					.getChild(root, i);

			if (model.isLeaf(child)) {
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) child
						.getParent();
				parent.remove(child);
				cc = model.getChildCount(parent);
				i--;
			}
		}

		model.reload();
	}

	private void cleanChordsParent(DefaultTreeModel model, Object root) {
		int cc;
		cc = model.getChildCount(root);

		for (int i = 0; i < cc; i++) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) model
					.getChild(root, i);

			int childSize = model.getChildCount(child);

			for (int j = 0; j < childSize; j++) {
				DefaultMutableTreeNode son = (DefaultMutableTreeNode) model
						.getChild(child, j);
				if (model.isLeaf(son)) {

					child.remove(son);
					childSize = model.getChildCount(child);
					j--;
				}
			}

		}

		model.reload();

	}

	private void Search4Artist(String str) {

		DefaultTreeModel model = (DefaultTreeModel) SongTree.getModel();
		if (model != null) {
			Object root = model.getRoot();
			walk4Artist(model, root, str);
			SongTree.setModel(model);
		} else
			System.out.println("Tree is empty.");

	}

	
	public String getSearchText() {

		return FindBox.getText();
	}

	public void switch2newSongPanel() {

		this.tabbedPane.setSelectedComponent(NewSongPanel);
		Cancel.setVisible(true);
		Modify.setVisible(true);
		btnGeneraPdf.setVisible(false);
		AddSongbutton.setVisible(false);

	}

	public void switch2CanzonierePanel() {

		this.tabbedPane.setSelectedComponent(CanzonierePanel);
		Cancel.setVisible(false);
		Modify.setVisible(false);
		btnGeneraPdf.setVisible(true);
		AddSongbutton.setVisible(true);

	}

	public Song getSelectedSong() {

		// prendo il testo del nodo
		String[] array = { "" };
		DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) SongTree
				.getLastSelectedPathComponent();
		if (selectedNode != null && selectedNode.isLeaf())
			array = getsongfromNode(selectedNode);
		String testo = "";
		for (String string : array) {
			testo = testo + string + "\n";
		}

		VisualizzazioneArea.setText(testo);
		String Artista = selectedNode.getParent().toString();
		String titolo = selectedNode.toString();

		Song selected = new Song(Artista, titolo, array);

		return selected;

	}

	public void selectRoot() {

		DefaultMutableTreeNode root = (DefaultMutableTreeNode) SongTree
				.getModel().getRoot();
		TreePath tp = new TreePath(root.getPath());
		SongTree.setSelectionPath(tp);
	}

	public void setModifyFields(Song selected) {

		ArtistBox.setText(selected.getSinger());
		titleBox.setText(selected.getTitle());

		String testo = "";
		for (String string : selected.getText()) {
			testo = testo + string + "\n";
		}
		TextArea.setText(testo);

	}

	private void checkIsLeaf(DefaultMutableTreeNode selected) {
		if (!selected.isRoot()) {
			if (!selected.isLeaf()) {
				btnModifica.setEnabled(false);
				btnDelete.setEnabled(false);
			} else {
				btnModifica.setEnabled(true);
				btnDelete.setEnabled(true);
			}
		}
	}

	public boolean isRoot(DefaultMutableTreeNode node) {

		DefaultMutableTreeNode root = (DefaultMutableTreeNode) SongTree
				.getModel().getRoot();

		if (node == root) {
			btnModifica.setEnabled(false);
			btnDelete.setEnabled(false);
			return true;
		} else {
			btnModifica.setEnabled(true);
			btnDelete.setEnabled(true);
			return false;
		}
	}

	public Chord getSelectedChord() {
		// prendo il testo del nodo

		DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) chordsTree
				.getLastSelectedPathComponent();
		if (selectedNode != null
				&& selectedNode.isLeaf()
				&& (!selectedNode.toString().equalsIgnoreCase("b")
						&& !selectedNode.toString().equalsIgnoreCase("#") && !selectedNode
						.toString().equalsIgnoreCase("STD"))) {

			DefaultMutableTreeNode padre = (DefaultMutableTreeNode) selectedNode
					.getParent();
			DefaultMutableTreeNode nonno = (DefaultMutableTreeNode) padre
					.getParent();

			String nonno_string = "";
			if (nonno.toString().equalsIgnoreCase("b"))
				nonno_string = "BEMOLLE";
			else if (nonno.toString().equalsIgnoreCase("#"))
				nonno_string = "DIESIS";
			else
				nonno_string = "STD";

			String padre_string = padre.toString();
			String nota_string = selectedNode.toString();

			noteType tipo = noteType.valueOf(nonno_string);
			Notes nota = Notes.valueOf(padre_string);

			Chord selected = new Chord(tipo, nota, nota_string);
			return selected;

		} else
			return null;
	}

	public void deleteChordImage() {
		if (picLabel != null)
			ChordPanel.remove(picLabel);
		ChordPanel.repaint();

	}

	public String getPath() {
		return PathTextField.getText();
	}

	public void setPath(String Path) {
		PathTextField.setText(Path);

	}

	public void setChordspath(String path) {
		
		chordsPathField.setText(path);

	}

	public String getChordspath() {
		return chordsPathField.getText();

	}

	public void setImagepath(String path) {
		ImagePathField.setText(path);

	}

	public String getImagepath() {
		return ImagePathField.getText();

	}

	public void saveSettings() {
		// creo la lista di settings da salvare
		if (this.getController() instanceof XMLController) {
			XMLManager manager = (XMLManager) this.getController()
					.getRegistredModel();
			manager.emptyList();
			manager.addElement(new Setting("PDFpath", false, getPath()));
			manager.addElement(new Setting("Chordspath", false, getChordspath()));
			
			String so = SOcomboBox.getSelectedItem().toString();
			if(so.equalsIgnoreCase("windows")){
				this.setPathSeparator("\\");
			}
			else
				this.setPathSeparator("/");
			manager.addElement(new Setting("SO", false, getPathSeparator()));
			
			manager.addElement(new Setting("AutoSave", getSalvataggioAutomatico(),"."));
			
			
			// Setto la lista del manager quella da salvare

			// genero l'XML
			manager.GenerateSettingsXML();
		}
	}

	public void saveDefaultSettings() {
		// creo la lista di settings da salvare
		if (this.getController() instanceof XMLController) {
			XMLManager manager = (XMLManager) this.getController()
					.getRegistredModel();
			manager.emptyList();
			manager.addElement(new Setting("PDFpath", false, "."));
			manager.addElement(new Setting("Chordspath", false, "."));
			manager.addElement(new Setting("SO", false, "/"));
			manager.addElement(new Setting("AutoSave", false, "."));

			// Setto la lista del manager quella da salvare

			// genero l'XML
			manager.GenerateSettingsXML();
		}
	}

	public void loadSettings() {
		if (this.getController() instanceof XMLController) {
			XMLManager manager = (XMLManager) this.getController()
					.getRegistredModel();
			manager.readSettingsXML();
			List<Setting> tmp = manager.getMySettings();
			for (Setting setting : tmp) {
				if (setting.getNome().equals("PDFpath") == true) {
					setPath(setting.getCampo());
				}
				if (setting.getNome().equals("Chordspath") == true) {
					setChordspath(setting.getCampo());
				}

				if (setting.getNome().equals("SO") == true) {
					setPathSeparator(setting.getCampo());
				}
				if (setting.getNome().equals("AutoSave") == true) {
					setAutoSave(setting.getValore());
				}

			}

		}

	}

	private void setAutoSave(Boolean valore) {
		
		checkBoxAutomatico.setSelected(valore);
	}

	public void setPathSeparator(String separator) {
		pathSeparator = separator;
	}

	public String getPathSeparator() {

		return pathSeparator;
	}

	public String getFindBoxText() {

		return FindBox.getText();
	}

	public boolean checkAddFields() {
		String artist = ArtistBox.getText().trim();
		String title = titleBox.getText().trim();
		String text = TextArea.getText().trim();

		if (artist.equals("") || title.equals("") || text.equals(""))
			return false;
		else
			return true;

	}

	public boolean checkAddChord() {

		String path = this.ImagePathField.getText().trim();
		if (path.equals(""))
			return false;
		else
			return true;
	}
}
